package br.pucrs.lognplay.repository.mapper.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import br.pucrs.lognplay.entity.User;
import br.pucrs.lognplay.repository.RepositoryException;
import br.pucrs.lognplay.repository.UserRepository;

public class UserMapper extends GenericMapper<User, String> implements UserRepository {

	public UserMapper() {
		super();
	}

	public UserMapper(EntityManager entityManager) {
		super(entityManager);
	}

	public User getByUsername(String username) throws RepositoryException {
		try {
			TypedQuery<User> typedQuery = getEntityManager().createQuery("SELECT user FROM User user WHERE user.username = :username", User.class);
			typedQuery.setParameter("username", username);

			try {
				return typedQuery.getSingleResult();
			} catch (NoResultException e) {
				return null;
			}
		} catch (Exception e) {
			throw new RepositoryException("Error on get user by username", e);
		}
	}

	public List<User> listByClientId(String clientId) throws RepositoryException {
		try {
			TypedQuery<User> typedQuery = getEntityManager().createQuery("SELECT user FROM User user WHERE user.client.id = :clientId", User.class);
			typedQuery.setParameter("clientId", clientId);
			return typedQuery.getResultList();
		} catch (Exception e) {
			throw new RepositoryException("Error on list users by client id", e);
		}
	}
}
